package com.lagou.sqlsession;

import com.lagou.pojo.Configuration;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MapperRegistry {

    private Configuration configuration;

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> T getMapper(Class<?> mapperClass, SqlSession sqlSession) {
        //使用JDK动态代理来为Dao接口生成代理对象
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                //底层还是执行jdbc
                //准备参数：1、statementId
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className+"."+methodName;

                MapperMethod mapperMethod = new MapperMethod(configuration);
                return mapperMethod.execute(sqlSession,method,statementId,objects);
                //参数2：params：args
                /*Type genericReturnType = method.getGenericReturnType();
                if (genericReturnType instanceof ParameterizedType){
                    List<Object> objectList = selectList(statementId, objects);
                    return objectList;
                }
                return selectOne(statementId,objects);*/
            }
        });
        return (T) proxyInstance;
    }
}
